package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.dto.StickyNoteRequest;
import com.ruoyi.livedemo.entity.StickyNote;
import com.ruoyi.livedemo.mapper.StickyNoteMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class StickyNoteService {

    private final StickyNoteMapper stickyNoteMapper;

    public PagedResult<StickyNote> list(Long userId, int page, int size) {
        int pageSize = size <= 0 ? 10 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<StickyNote> items = stickyNoteMapper.findPage(userId, offset, pageSize);
        long total = stickyNoteMapper.countByUser(userId);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public StickyNote create(Long userId, StickyNoteRequest request) {
        StickyNote note = new StickyNote();
        note.setUserId(userId);
        note.setTitle(request.getTitle());
        note.setContent(request.getContent());
        note.setColorHex(request.getColorHex());
        note.setPinned(Boolean.TRUE.equals(request.getPinned()));
        note.setExpiresAt(request.getExpiresAt());
        note.setCoverPath(request.getCoverPath());
        stickyNoteMapper.insert(note);
        return note;
    }

    @Transactional
    public StickyNote update(Long userId, Long id, StickyNoteRequest request) {
        StickyNote note = new StickyNote();
        note.setId(id);
        note.setUserId(userId);
        note.setTitle(request.getTitle());
        note.setContent(request.getContent());
        note.setColorHex(request.getColorHex());
        note.setPinned(Boolean.TRUE.equals(request.getPinned()));
        note.setExpiresAt(request.getExpiresAt());
        note.setCoverPath(request.getCoverPath());
        int rows = stickyNoteMapper.update(note);
        if (rows == 0) {
            throw new IllegalArgumentException("未找到对应的便签");
        }
        return note;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        stickyNoteMapper.delete(id, userId);
    }
}
